const fs = require('fs')
const path = require('path')
const queryFile = (file, position) => {
  return new Promise((resolve) => {
    fs.readFile(file.path, (err, data) => {
      if (!err) {
        const newFilePath = path.join(position, file.name)
        if (!fs.existsSync(position)) {
          fs.mkdir(newFilePath, (err) => {
            if (err) {
              console.error('Error creating folder:', err);
            }
          })
        }
        fs.writeFile(newFilePath, data, (err) => {
          if (!err) {
            resolve({
              success: 1,
              data: newFilePath,
              message: '上传成功！'
            })
          } else {
            resolve({
              success: 0,
              data: '',
              message: err
            })
          }
        })
      } else {
        resolve({
          success: 0,
          data: null,
          message: err
        })
      }

    })
  })

}
const savaEditConfig = (editConfig, configItem) => {
  const newConfig = { ...editConfig, ...configItem }
  const configPath = path.join(__dirname, 'editConfig.json')
  const jsonData = JSON.stringify(newConfig, null, 2);
  fs.writeFile(configPath, jsonData, 'utf-8', (err) => {
    console.log(err);
  })
}
const getEditConfig = () => {
  const configPath = path.join(__dirname, 'editConfig.json')
  return new Promise((resolve, reject) => {
    fs.readFile(configPath, 'utf-8', (err, data) => {
      if (!err) {
        resolve({
          success: 1,
          data: JSON.parse(data),
          message: '获取成功！'
        })
      } else {
        resolve({
          success: 1,
          data: null,
          message: err
        })
      }
    })
  })
}
const savaData = (path, data) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, 'utf-8', (err) => {
      if (!err) {
        resolve({
          success: 1,
          data: null,
          message: '保存成功！'
        })
      } else {
        resolve({
          success: 0,
          data: null,
          message: err
        })
      }
    })
  })
}
const getFileInfo = (path) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf-8', (err, data) => {
      if (!err) {
        resolve({
          success: 1,
          data: JSON.parse(data),
          message: '获取成功！'
        })
      } else {
        resolve({
          success: 0,
          data: null,
          message: err
        })
      }
    })
  })
}
module.exports = {
  queryFile,
  savaEditConfig,
  getEditConfig,
  savaData,
  getFileInfo
}